//
//  KLMyMessageViewController.m
//  used
//
//  Created by xalo on 16/7/26.
//  Copyright © 2016年 王凯. All rights reserved.
//

#import "KLMyMessageViewController.h"
#import "XFDaterView.h"

@interface KLMyMessageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextFieldDelegate, XFDaterViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UITextField *uname;

@property (weak, nonatomic) IBOutlet UILabel *account;

@property (weak, nonatomic) IBOutlet UITextField *birthField;
@property (weak, nonatomic) IBOutlet UITextField *address;
@property (weak, nonatomic) IBOutlet UITextField *phone;


/** 日期键盘 */
@property (nonatomic, strong) XFDaterView *dater;

@end

@implementation KLMyMessageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的资料";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定修改" style:UIBarButtonItemStyleDone target:self action:@selector(confirmChange)];
    
    
    self.birthField.delegate = self;
    
    BmobUser *user = [BmobUser getCurrentUser];
    self.account.text = [BmobUser getCurrentUser].username;
    if (user.username) {
        self.uname.text = [user objectForKey:@"uname"];
    }else {
        self.uname.text = user.username;
    }
    
    self.birthField.text = [user objectForKey:@"birthDay"];
    self.address.text = [user objectForKey:@"address"];
    self.phone.text = [user objectForKey:@"phone"];
    
    BmobFile *icon = [user objectForKey:@"icon"];
    [self.iconView sd_setImageWithURL:[NSURL URLWithString:icon.url]];
    

}

- (void)confirmChange {
    
    if (self.phone.text.length != 11) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showInfoWithStatus:@"手机号码有误!"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.0];
        return;
    }
    [self.view endEditing:YES];
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认修改" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    __weak KLMyMessageViewController *weakSelf = self;
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            BmobUser *user = [BmobUser getCurrentUser];
            [user setObject:weakSelf.uname.text forKey:@"uname"];
            [user setObject:weakSelf.birthField.text forKey:@"birthDay"];
            [user setObject:weakSelf.address.text forKey:@"address"];
            [user setObject:weakSelf.phone.text forKey:@"phone"];
            
            
            //     上传图片
            NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
            UIImage *image = [[ChangeImageSize defaultManager] imageCompressForSize:self.iconView.image targetSize:CGSizeMake(50, 50)];
            NSData *dataImage = UIImagePNGRepresentation(image);
            NSString *fileString = [documentsPath stringByAppendingPathComponent:@"icon.png"];
            
            [dataImage writeToFile:fileString atomically:YES];
            
            BmobFile *icon = [[BmobFile alloc] initWithFilePath:fileString];
            [icon saveInBackground:^(BOOL isSuccessful, NSError *error) {
                if (isSuccessful) {
                    [user setObject:icon forKey:@"icon"];
                    [user updateInBackground];
        
                }
            } withProgressBlock:^(CGFloat progress) {
    
            }];
            
        });
        
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:confirm];
    [alert addAction:action1];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)datePickerAction:(UIDatePicker *)sender {
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    
    NSString *dateStr = [fmt stringFromDate:sender.date];
    self.birthField.text = dateStr;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) { // 修改头像
        UIImagePickerController *pc = [[UIImagePickerController alloc]init];
        pc.delegate = self;
        [pc setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [pc setModalPresentationStyle:UIModalPresentationFullScreen];
        [pc setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
        [pc setAllowsEditing:YES];
        [self presentViewController:pc animated:YES completion:nil];
       
        
    }else if (indexPath.row == 3) { // 修改密码
       
        KLChangePwdViewController *changeVc = [[KLChangePwdViewController alloc] init];
        [self.navigationController pushViewController:changeVc animated:YES];
        
    }
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
   
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *image2 = [UIImage imagewithImage:image];
    self.iconView.image = image2;
  
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (navigationController.viewControllers.count == 3)
    {
        Method method = class_getInstanceMethod([self class], @selector(drawRect:));
        class_replaceMethod([[[[navigationController viewControllers][2].view subviews][1] subviews][0] class],@selector(drawRect:),method_getImplementation(method),method_getTypeEncoding(method));
    }
}


-(void)drawRect:(CGRect)rect
{
    CGContextRef ref = UIGraphicsGetCurrentContext();
    CGContextAddRect(ref, rect);
    CGContextAddArc(ref, [UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2, kScreenW/2, 0, M_PI*2, NO);
    [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]setFill];
    CGContextDrawPath(ref, kCGPathEOFill);
    
    CGContextAddArc(ref, [UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2, kScreenW/2, 0, M_PI*2, NO);
    [[UIColor whiteColor]setStroke];
    CGContextStrokePath(ref);
}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    self.dater = [[XFDaterView alloc]initWithFrame:CGRectZero];
    self.dater.delegate = self;
    [self.dater showInView:self.view animated:YES];
    
    return NO;
}
- (void)daterViewDidClicked:(XFDaterView *)daterView{
   
    self.birthField.text = self.dater.dateString;
}
@end
